const puppeteer = require('puppeteer')

const mongoose = require('mongoose')

const baseUrl = 'https://movie.douban.com/subject/'
const doubanId = '26100958'
const sleep = (time = 1000) => {
  return new Promise((res) => {
    setTimeout(res, time);
  })
}

const cp = require('child_process')
const { resolve } = require('path')

;
(async () => {
  const script = resolve(__dirname, './trailer-list')
  const child = cp.fork(script, [])
  let invoked = false

  child.on('error', err => {
    if (invoked) return

    invoked = true

    console.log(err)
  })

  child.on('exit', code => {
    if (invoked) return

    invoked = true
    let err = code === 0 ? null : new Error('exit code ' + code)

    console.log(err)
  })

  child.on('message', async data => {
    let Movie = mongoose.model('Movie')
    let movies = await Movie.find({
      $or: [
        { video: { $exists: false }}
      ]
      // doubanId: '30170448' // 
    })
    console.log('movies', movies) 
    // return
    movies.forEach(async movie => {
      const browser = await puppeteer.launch({
        args: ['--no-sandbox'],
        dumpio: false
      });

      const page = await browser.newPage();
      await page.goto(`${baseUrl}${movie.doubanId}`, {
        waitUntil: 'networkidle2'
      });

      await sleep(1000)

      const result = await page.evaluate(() => {
        var $ = window.$
        var it = $('a.related-pic-video')
        if (it && it.length > 0) {
          var link = it.attr('href')
          var cover = /\(\s*(.*?)\s*\)/.exec(it.attr('style'))[1]
          return {
            link,
            cover
          }
        }
        return {}
      })

      if (result.link) {
        await page.goto(result.link, {
          waitUntil: 'networkidle2'
        })
      }

      await sleep(1000)

      const video = await page.evaluate(() => {
        var $ = window.$
        var it = $('source')
        if (it && it.length > 0) {
          var video = it.attr('src')
          return video
        }
      })
      result.video = video
      result.poster = movie.poster
      result.doubanId = movie.doubanId

      movie.cover = result.cover
      movie.poster = result.poster
      movie.video = result.video
      await movie.save()
    })
    console.log('video爬取结束')
  })

})()



// (async () => {
//   const browser = await puppeteer.launch({
//     args: ['--no-sandbox'],
//     dumpio: false
//   });

//   const page = await browser.newPage();
//   await page.goto(`${baseUrl}${doubanId}`, {
//     waitUntil: 'networkidle2'
//   });

//   await sleep(1000)

  
//   const result = await page.evaluate(() => {
//     var $ = window.$
//     var it = $('a.related-pic-video')
//     if (it && it.length > 0) {
//       var link = it.attr('href')
//       var cover = /\(\s*(.*?)\s*\)/.exec(it.attr('style'))[1]
//       return {
//         link,
//         cover
//       }
//     }
//     return {}
//   })

//   if (result.link) {
//     await page.goto(result.link, {
//       waitUntil: 'networkidle2'
//     })
//   }

//   await sleep(1000)

//   const video = await page.evaluate(() => {
//     var $ = window.$
//     var it = $('source')
//     if (it && it.length > 0) {
//       var video = it.attr('src')
//       return video
//     }
//   })
//   result.video = video
//   result.doubanId = doubanId

//   browser.close()

//   process.send({ result })
//   console.log(result)

//   process.exit(0)

// })()
